package com.baosight.risk.common.exception;

import com.baosight.risk.api.code.ISqlCodeService;
import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.service.code.entity.SqlCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author duanyongqiang
 * <p>
 * 统一异常处理
 */
@Slf4j
@ControllerAdvice
public class DefaultExceptionHandler {

    @Autowired
    private ISqlCodeService sqlCodeService;

    /**
     * 拦截运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public AjaxResult notFount(RuntimeException e) {
        log.error("运行时异常:", e);
        List<SqlCode> listCode = sqlCodeService.queryAll();
        for (SqlCode code : listCode) {
            if (e.getMessage().contains("SQLSTATE=" + code.getSqlstate())) {
                return AjaxResult.error("系统异常：" + code.getExplain());
            }
        }
        return AjaxResult.error("系统异常，请联系管理员!");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AjaxResult handleException(Exception e) {
        log.error("服务器错误，请联系管理员", e);
        return AjaxResult.error("服务器错误: "+e);
    }
}
